﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

using Wicresoft.RDW.Presentation;
using Resources;


namespace Wicresoft.RDW.Account
{
    public partial class Login : BasePage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
            panel.DefaultButton = lbtnLogin.ID;
            txtUserName.Focus();
        }

        protected void LoadData()
        {
            ddlDomain.Items.Add("AD4");
            ddlDomain.Items.Add("AP01");
        }

        protected void lbtnLogin_Click(object sender, EventArgs e)
        {
            string userDomain = ddlDomain.SelectedValue;
            string userName = txtUserName.Text;
            string password = txtPassword.Text;
            string fullUserName = string.Format("{0}\\{1}", userDomain, userName);

            UserPresent userPresent = new UserPresent();
            if (!Utility.Helper.IsAlcatelMode() || userPresent.ImpersonateValidUser(userName, userDomain, password))
            {
                Model.User user = UserPresent.GetByCondition(p => p.Account == userName);
                try
                {
                    if (user != null)
                    {
                        //User Login Log
                        string desc = string.Format("[{0}] login in", userName);
                        SysLogPresent.Create(new Model.SysLog() { CreateBy = user.UserId, CreateTime = DateTime.Now, Desc = desc });

                        string userData = string.Format("{0}|{1}", user.UserId, userName);
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                           1, userName, DateTime.Now, DateTime.Now.AddHours(1), false, userData);

                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                        Response.Cookies.Add(cookie);

                        Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, true));
                    }
                    else
                    {
                        lblMessage.Text = CommonResource.LoginFailed;
                    }

                }
                catch (Exception ex)
                {
                    lblMessage.Text = ex.Message;
                }

               
            }
            else
            {
                lblMessage.Text = CommonResource.LoginFailed;
            }
        }

        public override void InitControlResource()
        {
            this.rfvUserName.ErrorMessage = Resources.NameResource.Message_InputUserName;
            this.rfvPassword.ErrorMessage = Resources.NameResource.Message_InputPassword;
        }
    }
}